package com.qf.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.common.http.Result;
import com.qf.entiy.dto.MerchantUser;

import com.qf.service.impl.MerchantUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("merchant")
public class MerchantUserController {

    @Autowired
    private MerchantUserService merchantUserService;

    //商家列表,查询所有
    @RequestMapping("list")
    public String toList(Model model,
                         @RequestParam(required = false) String query,
                         @RequestParam(required = false,defaultValue = "1")Long pageNum) {
        //搜索框()
        QueryWrapper<MerchantUser> wrapper = new QueryWrapper();
        if (!StringUtils.isEmpty(query)) {
            wrapper.lambda().like(MerchantUser::getName, query).or().like(MerchantUser::getUserName, query);
        }
        wrapper.lambda().orderByAsc(MerchantUser::getCreateTime);
        //分页
        IPage<MerchantUser> page = merchantUserService.page(new Page<>(pageNum, 1), wrapper);

        Long pages = page.getPages();
        List<Integer> pageList = new ArrayList<>(pages.intValue());
        for (int i = 1; i<= pages;i++){
            pageList.add(i);
        }
        model.addAttribute("pageList",pageList);
        model.addAttribute("merchantUserList", page.getRecords());
        return "merchant/list";
    }

    //根据ID查询用户[修改]
    @PostMapping("getById")
    @ResponseBody
    public Result<MerchantUser> getById(@RequestParam(value = "id", required = true) Long id) {
        return Result.success(merchantUserService.getById(id));
    }

    //新增or修改
    @PostMapping("save")
    @ResponseBody
    public Result<?> save(MerchantUser merchantUser) {
        merchantUserService.saveOrUpdate(merchantUser);
        return Result.success();
    }

    //删除
    @PostMapping("del")
    @ResponseBody
    public Result<?> del(@RequestParam(value = "id") Long id) {
        merchantUserService.removeById(id);
        return Result.success();
    }

}
